package com.bhs.sansong.ui.shipments;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bhs.sansong.R;
import com.bhs.sansong.adapter.HistoricalAddressAdapter;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.bean.AddressInfo;
import com.bhs.sansong.bean.AddressList;
import com.bhs.sansong.bean.CommonBean;
import com.bhs.sansong.bean.DetailedAddressBean;
import com.bhs.sansong.bean.LocationBean;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.other.LocationSelectionActivity;
import com.bhs.sansong.utils.LogUtils;
import com.bhs.sansong.utils.MyUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.Map;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

/**
 * 填写地址
 */
public class CompleteAddressActivity extends BaseActivity implements View.OnClickListener, TextWatcher, NetCallBack {

    private int type;//1选择出发地址
    private String addressType = "";
    private TextView mTvSign;
    private EditText mEtName;
    private EditText mEtPhone;
    private TextView mTvCity;
    private EditText mEtAddress;
    private EditText mEtCompanyName;
    private CheckBox mCbAgreement;
    private TextView mTvEmpty;
    private RecyclerView mRvList;
    private HistoricalAddressAdapter mAdapter;
    private Button mBtnConfirm;
    private TextView mTvHistoricalAddress;
    private TextView mTvTitle;
    private LocationBean locationBean;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private TextView mTvStatus;
    private int addressId;
    private EditText mEtDetailedAddress;
    private TextView mTvRecognize;

    @Override
    public int initLayout() {
        return R.layout.activity_complete_address;
    }

    @Override
    public void initView() {
        addressId = getIntent().getIntExtra("id", 0);
        type = getIntent().getIntExtra("type", 0);
        mTvTitle = findViewById(R.id.tv_title);
        mTvEmpty = findViewById(R.id.tv_empty);
        mTvSign = findViewById(R.id.tv_sign);
        mEtName = findViewById(R.id.et_name);
        mEtPhone = findViewById(R.id.et_phone);
        mTvCity = findViewById(R.id.tv_city);
        mEtAddress = findViewById(R.id.et_address);
        mEtCompanyName = findViewById(R.id.et_company_name);
        mCbAgreement = findViewById(R.id.cb_agreement);
        mRvList = findViewById(R.id.rv_list);
        mBtnConfirm = findViewById(R.id.btn_confirm);
        mBtnConfirm.setOnClickListener(this);
        mTvEmpty.setOnClickListener(this);
        mTvCity.setOnClickListener(this);
        mTvHistoricalAddress = findViewById(R.id.tv_historical_address);
        mEtDetailedAddress = findViewById(R.id.et_detailed_address);
        mTvRecognize = findViewById(R.id.tv_recognize);
        mTvRecognize.setOnClickListener(this);
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    locationBean = result.getData().getParcelableExtra("location");
                    mTvCity.setText(String.format("%s-%s-%s", locationBean.getProvince(), locationBean.getCity(), locationBean.getCounty()));
                    mEtAddress.setText(locationBean.getAddress());
                    verify();
                }
            }
        });
        mTvStatus = findViewById(R.id.tv_status);
        if (addressId > 0) {
            networkRequest(netApi.get_address_detail(addressId), this, 888);
        }

        mEtDetailedAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                networkRequest(netApi.pca_format("cargo", mEtDetailedAddress.getText().toString()), CompleteAddressActivity.this, 999);
            }
        });

    }

    @Override
    public void initData() {
        mEtAddress.addTextChangedListener(this);
        mEtCompanyName.addTextChangedListener(this);
        mEtName.addTextChangedListener(this);
        mEtPhone.addTextChangedListener(this);
        mAdapter = new HistoricalAddressAdapter();
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(mActivity));
        if (type == 1) {
            mTvTitle.setText("发货地址填写");
            loadData();
            addressType = "pickiup";
        } else if (type == 2) {
            mTvTitle.setText("收货地址填写");
            mTvSign.setBackgroundResource(R.drawable.bg_oval_yellow);
            mTvSign.setText("收");
            mTvStatus.setText("收货人");
            addressType = "receive";
            loadData();
        } else if (type == 3) {
            mTvSign.setVisibility(View.GONE);
            mTvTitle.setText("添加地址");
            mTvStatus.setText("联系人信息");
        } else if (type == 4) {
            mTvSign.setVisibility(View.GONE);
            mTvTitle.setText("修改地址");
            mTvStatus.setText("联系人信息");
        }
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent i = new Intent();
                i.putExtra("info", mAdapter.getData().get(position));
                setResult(getIntent().getIntExtra("type", 0), i);
                finish();
            }
        });
    }

    Map<String, String> map = new ArrayMap<>();

    private void loadData() {
        map.put("page", "1");
        networkRequest(netApi.get_address_list(map), this, 9527);
    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    private void verify() {
        boolean verify = true;
        if (TextUtils.isEmpty(mEtName.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtPhone.getText()) || TextUtils.isEmpty(mEtAddress.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mTvCity.getText())) {
            verify = false;
        }

        mBtnConfirm.setEnabled(verify);
        mBtnConfirm.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }


    @Override
    public void onClick(View view) {
        Map<String, String> map = new ArrayMap<>();
        if (view.getId() == R.id.btn_confirm) {
            loadingPopupShow();
            map.put("truename", mEtName.getText().toString());
            map.put("mobile", mEtPhone.getText().toString());
            map.put("address", mEtAddress.getText().toString());
            map.put("remark", mEtCompanyName.getText().toString());
            map.put("province", locationBean.getProvince());
            map.put("city", locationBean.getCity());
            map.put("county", locationBean.getCounty());
            map.put("latitude", String.valueOf(locationBean.getLatitude()));
            map.put("longitude", String.valueOf(locationBean.getLongitude()));
            map.put("is_default", mCbAgreement.isChecked() ? "1" : "0");
            map.put("address_type", addressType);
            map.put("is_temp", "1");
            if (!mTvTitle.getText().toString().equals("修改地址")) {
                networkRequest(netApi.add_address(map), this);
            } else {
                map.put("address_id", String.valueOf(addressId));
                networkRequest(netApi.edit_address(map), this);
            }
        } else if (view.getId() == R.id.tv_city) {
            methodRequiresTwoPermission();
        } else if (view.getId() == R.id.tv_recognize) {
            //获取系统剪贴板服务
            ClipboardManager clipboardManager = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
            if (null != clipboardManager) {
                // 获取剪贴板的剪贴数据集
                ClipData clipData = clipboardManager.getPrimaryClip();
                if (null != clipData && clipData.getItemCount() > 0) {
                    // 从数据集中获取（粘贴）第一条文本数据
                    ClipData.Item item = clipData.getItemAt(0);
                    if (null != item) {
                        String content = item.getText().toString();
                        mEtDetailedAddress.setText(content);
                    }
                }
            }
        }
    }

    String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE};
    public static final int RC_LOCATION = 1; // requestCode

    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            intentActivityResultLauncher.launch(new Intent(mActivity, LocationSelectionActivity.class));
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "我需要您的位置信息",
                    RC_LOCATION, perms);
        }
    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 9527) {
            AddressList addressList = new Gson().fromJson(json, AddressList.class);
            if (addressList.isStatus()) {
                if (!MyUtils.isEmpty(addressList.getData().getAddressInfoList())) {
                    mTvHistoricalAddress.setVisibility(View.VISIBLE);
                    mAdapter.setNewData(addressList.getData().getAddressInfoList());
                }
            }
        } else if (requestCode == 888) {
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.getBoolean("status")) {
                JSONObject data = new JSONObject(jsonObject.getString("data"));
                String info = data.getString("info");
                AddressInfo addressInfo = new Gson().fromJson(info, AddressInfo.class);
                mEtName.setText(addressInfo.getTruename());
                mEtPhone.setText(addressInfo.getMobile());
                mTvCity.setText(String.format("%s-%s-%s", addressInfo.getProvince(), addressInfo.getCity(), addressInfo.getCounty()));
                mEtAddress.setText(addressInfo.getAddress());
                mEtCompanyName.setText(addressInfo.getRemark());
                mCbAgreement.setChecked(addressInfo.getIs_default() == 1);
                locationBean = new LocationBean("", addressInfo.getAddress()
                        , Double.parseDouble(addressInfo.getLatitude()),
                        Double.parseDouble(addressInfo.getLongitude()), addressInfo.getProvince(), addressInfo.getCounty(), addressInfo.getCity());
            }
        } else if (requestCode == 999) {
            DetailedAddressBean bean = new Gson().fromJson(json, DetailedAddressBean.class);
            if (bean.isStatus()) {
                DetailedAddressBean.DataDTO data = bean.getData();
                mEtName.setText(data.getName());
                mEtPhone.setText(data.getMobile());
                mTvCity.setText(String.format("%s-%s-%s", data.getProvince(), data.getCity(), data.getRegion()));
                mEtAddress.setText(data.getStreet());
                if (!TextUtils.isEmpty(data.getStreet())) {
                    getLatlon(data.getProvince() + data.getCity() + data.getRegion() + data.getStreet());
                }
            }
        } else {
            loadingPopupDismiss();
            CommonBean bean = new Gson().fromJson(json, CommonBean.class);
            if (bean.isStatus()) {
                AddressInfo addressInfo = new AddressInfo(locationBean.getCity(), mEtName.getText().toString(),
                        mEtPhone.getText().toString(), mEtAddress.getText().toString(), bean.getData().getId());
                Intent i = new Intent();
                i.putExtra("info", addressInfo);
                setResult(getIntent().getIntExtra("type", 0), i);
                finish();
            } else {
                ToastUtil.show(bean.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void getLatlon(String cityName) {

        GeocodeSearch geocodeSearch = null;
        try {
            geocodeSearch = new GeocodeSearch(this);
        } catch (AMapException e) {
            throw new RuntimeException(e);
        }
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                if (i == 1000) {
                    if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                            geocodeResult.getGeocodeAddressList().size() > 0) {
                        GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                        double longitude = geocodeAddress.getLatLonPoint().getLongitude();
                        double latitude = geocodeAddress.getLatLonPoint().getLatitude();
                        String province = geocodeAddress.getProvince();
                        String city = geocodeAddress.getCity();
                        String county = geocodeAddress.getCountry();
                        locationBean = new LocationBean("", mEtAddress.getText().toString(), latitude,
                                longitude, province, county, city);
                    } else {
                        Toast.makeText(mActivity, "地名出错", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        GeocodeQuery geocodeQuery = new GeocodeQuery(cityName.trim(), "29");
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);

    }

}